package com.wg.msshopsp.controller;

import com.wg.msshopsp.entity.Review;
import com.wg.msshopsp.entity.ReviewForm;
import com.wg.msshopsp.entity.ReviewUserDTO;
import com.wg.msshopsp.service.ReviewService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Tag(name = "ReviewController", description = "评价管理")
@RestController
public class ReviewController {
    @Autowired
    private ReviewService reviewService;

    @PostMapping("/shop/review")
    @Operation(summary = "新增评价")
    public int insert(@RequestBody Review review){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        review.setCreateTime(sdf.format(new Date()));
        return reviewService.save(review)?1:0;
    }

    @DeleteMapping("/shop/review")
    @Operation(summary = "删除评价")
    public int delete(@Parameter Integer id){
        return reviewService.removeById(id)?1:0;
    }

    @PutMapping("/shop/review")
    @Operation(summary = "修改评价")
    public int update(@RequestBody Review review){
        return reviewService.updateById(review)?1:0;
    }

    @GetMapping("/shop/review")
    @Operation(summary = "查询评价")
    public Review select(@Parameter Integer id){
        return reviewService.getById(id);
    }

    @GetMapping("/shop/review/list/{productId}")
    @Operation(summary = "查询店铺评价列表(默认排序)")
    public List<ReviewUserDTO> getReviewUserInfo(@PathVariable("productId") Integer productId){
        return reviewService.getReviewUserInfo(productId);
    }

    @GetMapping("/shop/review/list/time")
    @Operation(summary = "查询店铺评价列表(时间排序)")
    public List<ReviewUserDTO> getReviewUserInfoByTime(@Parameter Integer shopId){
        return reviewService.getReviewUserInfoByTime(shopId);
    }



    //==================================
    @PostMapping("/shop/review/add")
    @Operation(summary = "发表评价")
    public String addReview(@RequestBody ReviewForm form) {
        try {
            // 直接使用前端传递的userId（无任何身份验证）
            Integer userId = form.getUserId();
            if (userId == null) {
                return "评价失败：用户ID不能为空";
            }

            reviewService.addReview(form, userId);
            return "评价发表成功！";

        } catch (RuntimeException e) {
            return "评价失败：" + e.getMessage();
        }
    }
}
